package cn.wolfcode.luowowo.search.service.impl;

import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.repository.StrategyMongoRepository;
import cn.wolfcode.luowowo.search.service.IStrategySearchService;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.vo.StatsResult;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregation;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder;
import org.elasticsearch.search.aggregations.bucket.composite.TermsValuesSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.*;

@Service
public class StrategySearchServiceImpl implements IStrategySearchService {
    @Autowired
    private StrategyMongoRepository repository;

    @Override
    public void save(StrategyTemplate template) {
        repository.save(template);
    }

    @Override
    public List<StatsResult> listConditions(int condition) {
        String id = null;
        String name = null;
        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                id = "provinceId";
                name = "provinceName";
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                id = "countryId";
                name = "countryName";
                break;
            case SearchQueryObject.CONDITION_THEME:
                id = "themeId";
                name = "themeName";
                break;
        }
        return groupCondition(id,name,condition);
    }

    @Override
    public Page<StrategyTemplate> query(SearchQueryObject qo) {
        Page<StrategyTemplate> page = null;
        switch (qo.getType()){
            case SearchQueryObject.CONDITION_UNABROAD :
                page = repository.findByProvinceId(qo.getTypeValue(), qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_ABROAD :
                page = repository.findByCountryId(qo.getTypeValue(), qo.getPageable());
                break;
            case SearchQueryObject.CONDITION_THEME :
                page = repository.findByThemeId(qo.getTypeValue(),qo.getPageable());
                break;
            default:
                page = repository.findAll(qo.getPageable());
        }
        return page;
    }


    private List<StatsResult> groupCondition(String id, String name, int condition) {
        String groupType = "groupType";
        String idField = "id";
        String nameField = "name";

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withPageable(PageRequest.of(0, 1));
        switch (condition) {
            case SearchQueryObject.CONDITION_UNABROAD:
                //CONDITION_UNABROAD->排除非中国数据
                builder.withQuery(QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID));
                break;
            case SearchQueryObject.CONDITION_ABROAD:
                //CONDITION_ABROAD->排除中国数据
                builder.withQuery(
                        QueryBuilders.boolQuery()
                                .mustNot(
                                        QueryBuilders.termQuery("countryId", StatsResult.CHINA_ID)
                                )
                );
                break;
        }

        //多维度桶聚合条件
        List<CompositeValuesSourceBuilder<?>> sources = new ArrayList<>();

        sources.add(new TermsValuesSourceBuilder(idField).field(id));
        sources.add(new TermsValuesSourceBuilder(nameField).field(name));

        CompositeAggregationBuilder group = new CompositeAggregationBuilder(groupType, sources);

        builder.addAggregation(group);
        AggregatedPage<StrategyTemplate> page = (AggregatedPage<StrategyTemplate>) repository.search(builder.build());

        //拿到分组结果
        CompositeAggregation aggs = (CompositeAggregation) page.getAggregation(groupType);

        List<StatsResult> list = new ArrayList<>();
        for (CompositeAggregation.Bucket bucket : aggs.getBuckets()) {
            Map<String, Object> key = bucket.getKey();
            Object idValue = key.get(idField);
            Object nameValue = key.get(nameField);
            long count = bucket.getDocCount();
            list.add(new StatsResult(Long.parseLong(idValue.toString()), nameValue.toString(), count));
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> themeCommends() {
        List<Map<String, Object>> list = new ArrayList<>();
        //调用桶聚合
        List<StatsResult> results = groupCondition("themeId", "themeName", 0);
        if (results != null) {
            for (StatsResult result : results) {
                Map<String,Object> map = new HashMap<>();
                map.put("theme",result);
                //获取id
                Long id = result.getId();
                //主题id获取攻略
                List<StrategyTemplate> sts = repository.findByThemeId(id, null).getContent();
                //目的地集合
                Set<StatsResult> set = new HashSet<>();
                if (sts != null) {
                    for (StrategyTemplate st : sts) {
                        set.add(new StatsResult(st.getDestId(),st.getDestName(),null));
                    }
                }
                map.put("dests",set);
                list.add(map);
            }
        }
        return list;
    }

    @Override
    public List<StrategyTemplate> listByDestName(String keyword) {
        return repository.findByDestName(keyword);
    }

}
